'''
平安成人重大疾病保险
'''
import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "平安成人重大疾病保险"

    # 生产产品数据
    def genProductInfo(self):
        plan = {
            # 年龄段
            "year": [str(i) for i in range(18, 51)],
            # 性别
            "gender": ["M", "F"],
            # 保额
            "money": ["10000", "50000", "100000", "200000", "300000", "500000"],
            # 保障期限
            "expire": ["1年"],
        }
        for v in product(plan["year"], plan["gender"], plan["money"], plan["expire"]):
            # 写入数据库
            self.mysql.cursor.execute(

                domain[self.name]["insert_sql"].format(

                    v[0], v[1], v[2], v[3]
                )
            )
            self.mysql._conn.commit()

            print(

                domain[self.name]["insert_sql"].format(

                    v[0], v[1], v[2], v[3]
                )
            )

    # 执行爬虫
    def requestJson(self, dt=None):

        if 18<=int(dt["year"])<=20:

            code = "90"

        elif 21<=int(dt["year"])<=25:

            code = "91"

        elif 26<=int(dt["year"])<=30:

            code = "92"
        elif 31 <= int(dt["year"]) <=35:

            code = "93"

        elif 36 <= int(dt["year"]) <= 40:

            code = "94"

        elif 41 <= int(dt["year"]) <= 45:

            code = "95"

        else:
            code = "96"

        data = {"insurantNum": [{"personNum": "1", "subjectType": code}],
                "effectDate": {"addDays": "", "endDate": "2021-01-21", "beginDate": "2020-01-22"},
                "planPackage": {"marketProductCode": "MP03000402", "packageCode": "00000"},
                "applyPeriod": {"term": 12, "termUnit": "M"}, "planDuty": [
                {"planCode": "PL03J0072", "value": dt["money"], "subjectType": code, "dutyName": "重大疾病保险金",
                 "dutyCode": "CVJC009"}], "planSex": "01" if dt["gender"] == "M" else "02",
                "flowId": "B0MB6XTiGiDK9RJQ"}



        payload = json.dumps(data)

        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)

        if r.status_code == 200 and "处理成功" in r.text:

            price = Helper.decimalParse(r.json()["quoteResult"][0]["actualPremium"])

            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )

        else:

            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )

            print("/*产品价格更新失败:%d*/"%dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)

